/**
 * 根据parentId字段关联父子关系生成tree结构数据
 */
export function mergeByParentId(data, cascadeField = 'children') {
  let temp = null;
  const len = data.length; // 6
  if (data && len > 0) {
    for (let i = 0; i < len - 1; i++) { // i=0时j循环5次、i=1时j循环4次、i=2时j循环3次、i=3时j循环2次、i=4时j循环1次
      for (let j = i + 1; j < len; j++) {
        if (data[i].parentId === 'root') {
          break;
        }
        if (data[i].parentId === data[j].id) {
          if (data[j][cascadeField] == null) {
            data[j][cascadeField] = [];
          }
          temp = data[i];
          data[j][cascadeField].push(temp);
          data[i] = null;
          break;
        }
      }
    }
    temp = null;
    /**
     * 过滤已经匹配成功的数组：删除数组中元素为null的元素
     */
    data = data.filter(item => {
      if (item) {
        // if (item.parentId === 'root' && item.children) { item.src = ''; }
        return true;
      } else {
        return false;
      }
    });
    return data;
  }
  return [];
}

/**
 * 获取tree节点以及其所有后代元素的id
 */
let treeNodeIds = [];
const recursiveId = function (node) {
  if (node) {
    treeNodeIds.push(node.id);
    if (node.children) {
      const len = node.children.length;
      for (let i = 0; i < len; i++) {
        recursiveId(node.children[i]);
      }
    }
  }
};

export function getTreeNodeIds(node) {
  treeNodeIds = [];
  recursiveId(node);
  return treeNodeIds;
}

/**
 * 数组a减去数组b
 */
export function arraySubtracting(a, b) {
  const len = b.length;
  for (let i = 0; i < len; i++) {
    const index = a.indexOf(b[i]);
    if (index > -1) {
      a.splice(index, 1);
    }
  }
  return a;
}

/**
 * 获取当前时间并转化成2018-09-14 08:08:08格式字符串
 */
export function dataTimeStr() {
  let date = new Date();
  let y = date.getFullYear();
  let MM = date.getMonth() + 1;
  MM = MM < 10 ? ('0' + MM) : MM;
  let d = date.getDate();
  d = d < 10 ? ('0' + d) : d;
  let h = date.getHours();
  h = h < 10 ? ('0' + h) : h;
  let m = date.getMinutes();
  m = m < 10 ? ('0' + m) : m;
  let s = date.getSeconds();
  s = s < 10 ? ('0' + s) : s;
  return y + '-' + MM + '-' + d + ' ' + h + ':' + m + ':' + s;
}

